package com.lanou3g.k12.service.impl;

import com.lanou3g.k12.entity.Orders;
import com.lanou3g.k12.service.OrdersCourseService;
import com.lanou3g.k12.vo.OrdersFind;
import com.lanou3g.k12.mapper.OrdersMapper;
import com.lanou3g.k12.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersCourseService ordersCourseService;

    /**
     * 通过id查询订单
     *
     * @param id 订单表id
     * @return
     */
    @Override
    public Orders findById(Integer id) {
        Orders order = ordersMapper.findById(id);
        return order;
    }

    /**
     * 多条件查询
     *
     * @param ordersFind 参数对象
     * @return
     */
    @Override
    public List<Orders> find(OrdersFind ordersFind) {

        if (ordersFind.getKeyword() == null) {
            ordersFind.setKeyword(null);
        } else {
            // 字符串拼接
            ordersFind.setKeyword("%" + ordersFind.getKeyword() + "%");
        }

        ordersFind.setBegintime(ordersFind.getBegintime());
        ordersFind.setEndtime(ordersFind.getEndtime());
        List<Orders> ordersList = ordersMapper.find(ordersFind);

        return ordersList;
    }

    @Override
    public List<Orders> findByDate(String format, String format1) {
        List<Orders> byDate = ordersMapper.findByDate(format, format1);
        return byDate;
    }

    /**
     * 订单表插入一条数据，中间表多一条cid，oid
     *
     * @param orders 订单对象
     * @param csId   课程id
     * @return
     */
    @Override
    public int add(Orders orders, Long csId) {

        Date date = new Date();
        orders.setBeginTime(date);
        orders.setEndTime(date);
        orders.setCreateTime(date);
        orders.setUpdateTime(date);

        // 插入Order表
        orders.setUid(orders.getUid());
        int insert = ordersMapper.orderInsert(orders);

        // 插入中间表
        Long odId = orders.getId();
        ordersCourseService.insert(odId, csId);

        return insert;
    }

    /**
     * 通过课程id查询订单
     *
     * @param cid 课程id
     * @return
     */
    @Override
    public List<Orders> findByCid(int cid) {
        List<Orders> byCid = ordersMapper.findByCid(cid);
        return byCid;
    }

    /**
     * 查询我的订单
     *
     * @param uid    用户id
     * @param status 支付状态
     * @return
     */
    @Override
    public List<Orders> findOrders(Long uid, Integer status) {

        if (status != null) {
            List<Orders> ordersList = ordersMapper.findOrders(uid, status);
            return ordersList;
        } else {
            List<Orders> ordersList = ordersMapper.findOrderss(uid);
            return ordersList;
        }
    }
}
